//
//  VCodeViewController.swift
//  ShiZhe
//
//  Created by 陈卿伟 on 16/8/29.
//  Copyright © 2016年 陈卿伟. All rights reserved.
//

import UIKit
import Alamofire
import SwiftyJSON

class VCodeViewController: MainViewController {
    
    var phoneNum:String!//上级页面传过来的电话号码
    var password:String!//上级传过来的密码
    var vCodeView:VCodeView!
    var timeN = 60//读秒
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "验证码"
        self.addVCodeView()
        self.initForVCodeView()
    }
}



//MARK:--UI设置
extension VCodeViewController{
    //加入view
    func addVCodeView(){
        vCodeView = VCodeView(frame: MainBounds)
        self.view.addSubview(vCodeView)
    }
    
    
    //为vcodeview上的控件添加点击事件和赋值
    func initForVCodeView(){
        //为电话号码label赋值
        vCodeView.phoneLabel.text = phoneNum
        
        //为发送验证码添加点击事件
        let proButton = vCodeView.provingButton
        proButton?.addTarget(self, action: #selector(self.provingButtonClick(_:)), forControlEvents: .TouchUpInside)
        NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(self.timeValueChanged(_:)), userInfo: proButton, repeats: true)
        
        //为注册按钮添加点击事件
        vCodeView.registerButton.addTarget(self, action: #selector(self.registerButtonClick(_:)), forControlEvents: .TouchUpInside)
    }
}


//MARK:--点击事件
extension VCodeViewController{
    //重新发送验证码点击事件
    func provingButtonClick(sender:UIButton){
        sender.userInteractionEnabled = false
        if let hud = self.view.window!.viewWithTag(999) as? WaitHUD{
            SMSSDK.getVerificationCodeByMethod(SMSGetCodeMethodSMS, phoneNumber: phoneNum, zone: "86", customIdentifier: nil) { (error) in
                hud.alpha = 0
                if error == nil{
                    NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(self.timeValueChanged(_:)), userInfo: sender, repeats: true)
                    self.timeN = 60
                }else{
                    let userInfo = error.userInfo["getVerificationCode"] as! String
                    showHUD.showTopHud(self.view, text: userInfo)
                    sender.userInteractionEnabled = true
                }
            }
        }
    }
    
    //点击发送验证码的时候 provingButton的时间转换事件
    func timeValueChanged(sender:NSTimer){
        let proButton = sender.userInfo as! UIButton
        if timeN == 60{
            proButton.backgroundColor = UIColor(red: 192/255, green: 192/255, blue: 192/255, alpha: 1)
        }
        proButton.setTitle("重新发送 (\(timeN)s)", forState: UIControlState())
        
        if timeN == 0{
            proButton.backgroundColor = UIColor.redColor()
            proButton.setTitle("发送验证码", forState: UIControlState())
            proButton.userInteractionEnabled = true
            sender.invalidate()
        }
        
        timeN -= 1
    }
    
    
    //确定注册按钮点击事件
    func registerButtonClick(sender:UIButton){
        let proTextF = vCodeView.provingTextField
        proTextF?.resignFirstResponder()
        if let hud = self.view.window!.viewWithTag(999) as? WaitHUD{
            hud.alpha = 1
            SMSSDK.commitVerificationCode(proTextF?.text, phoneNumber: phoneNum, zone: "86") { (error) in
                if error == nil{
                    self.registerAlamofire(hud)
                }else{
                    hud.alpha = 0
                    let userInfo = error.userInfo["commitVerificationCode"] as! String
                    showHUD.showTopHud(self.view, text: userInfo)
                }
            }
        }
    }
}


//MARK:--Alamofire
extension VCodeViewController{
    //注册的Alamofire
    func registerAlamofire(hud:WaitHUD){
        let parameters = ["phone":phoneNum,"password":password]
        Alamofire.request(.POST, "http://srxapp.zhekd.com/ios.php/Login/regist", parameters: parameters, encoding: .JSON).responseJSON { (data) in
            let json = JSON(data: data.data!)
            let code = json["code"].stringValue
            let message = json["message"].stringValue
            print(json)
            print(message)
            if code == "1"{
                self.logInAlamofire(self.phoneNum, password: self.password,hud: hud)
            }else{
                hud.alpha = 0
                showHUD.showTopHud(self.view, text: message)
            }
        }
    }
    
    //登录的Alamofire
    func logInAlamofire(phone:String,password:String,hud:WaitHUD){
        let parameters = ["phone":phone,"password":password]
        Alamofire.request(.POST, "http://srxapp.zhekd.com/ios.php/Login/login", parameters: parameters, encoding: .JSON).responseJSON { (data) in
            let json = JSON(data: data.data!)
            let code = json["code"].stringValue
            let message = json["message"].stringValue
            if code == "1"{
                hud.alpha = 0
                let token = json["token"].stringValue
                let userID = json["user_id"].stringValue
                let userInfo = UserInfo(token: token,userID: userID, phoneNum: phone, password: password, userName: "YOUKNOWWHO", avatar: "", gender: "YOUKNOWSEX", birthday: "YOUKNOWDAY", signature: "YOUKNOWENHENG")
                OperateUserDefaults.deleteUserDefault()
                OperateUserDefaults.saveUserDefault(userInfo)
                self.navigationController?.pushViewController(DataFillViewController(), animated: true)
            }else{
                hud.alpha = 0
                showHUD.showTopHud(self.view, text: message)
            }
        }
    }
}



















